package com.qd.panda.wallet.plan;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.ApiResultWrapper;
import com.cdqidi.dto.DelDTO;
import com.cdqidi.util.page.PageUtil;
import com.cdqidi.valid.group.DefaultGroup;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qd.common.sys.annotation.OperatorInfo;
import com.qd.common.sys.enums.OperatorType;
import com.qd.common.sys.util.SecurityUtils;
import com.qd.common.panda.domain.entity.wallet.publish.PlanPublishDTO;
import com.qd.panda.model.PlanPublishList;
import com.qd.panda.service.wallet.publish.PlanPublishService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 钱包/套餐/WEB_发布套餐
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/sys/wallet/planPublish/")
@Slf4j
public class PlanPublishController {
    private final PlanPublishService planPublishService;
    private final ObjectMapper objectMapper;

    /**
     * 添加
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @PreAuthorize("@ps.hasPermission('system:planPublish:save')")
    @OperatorInfo(title = "添加", operator = OperatorType.INSERT)
    @PostMapping(value = "/save")
    public PlanPublishDTO save(@Validated({DefaultGroup.class}) @RequestBody PlanPublishDTO dto) {
        dto.setPublishId(IdWorker.getIdStr());
        dto.setAddTime(LocalDateTime.now());
        dto.setOperator(SecurityUtils.getLoginUser().getUserId());
        dto.setOperateOrgId(SecurityUtils.getLoginUser().getCurrentOrgId());
        if (!StringUtils.hasLength(dto.getEnable())) {
            dto.setEnable(ConstantDto.SF1);
        }
        return planPublishService.save(dto);
    }

    /**
     * 删除
     *
     * @param delDTO delDTO中的ids,主键
     * @return 成功 or 失败
     */
    @PreAuthorize("@ps.hasPermission('system:planPublish:delete')")
    @OperatorInfo(title = "删除", operator = OperatorType.DELETE)
    @DeleteMapping(value = "/delete")
    public ApiResultWrapper<Object> delete(@Validated @RequestBody DelDTO<String> delDTO) {
        List<String> ids = delDTO.getIds();
        if (ids.size() == 1) {
            planPublishService.removeById(ids.get(0));
        } else {
            planPublishService.removeBatchIds(ids);
        }
        return ApiResult.success("删除成功");
    }

    /**
     * 开启关闭
     *
     * @param dto 参数
     * @return 成功 or 失败
     */
    @PreAuthorize("@ps.hasPermission('system:planPublish:enable')")
    @OperatorInfo(title = "开启关闭", operator = OperatorType.OTHER)
    @PutMapping(value = "/enable")
    public ApiResultWrapper<Object> enable(@Validated @RequestBody PlanPublishDTO dto) {
        if (!StringUtils.hasLength(dto.getPublishId())) {
            return ApiResult.error("套餐发布ID不能为空");
        }
        if (!StringUtils.hasLength(dto.getEnable())) {
            return ApiResult.error("是否启用不能为空");
        }
        dto.setUpdateTime(LocalDateTime.now());
        dto.setOperateOrgId(SecurityUtils.getLoginUser().getCurrentOrgId());
        dto.setOperator(SecurityUtils.getLoginUser().getUserId());
        planPublishService.enable(dto);
        dto.freeData();
        return ApiResult.success("操作成功");
    }

    /**
     * 详情
     *
     * @param id 主键
     * @return 记录
     */
    @GetMapping(value = "/getById")
    public PlanPublishDTO getById(@Validated @NotBlank(message = "ID不能为空") String id) {
        return planPublishService.getByIdDto(id);
    }

    /**
     * 列表
     *
     * @param dto 查询参数以及页数和每页显示条数
     * @return 列表信息
     */
    @GetMapping(value = "/page")
    public IPage<PlanPublishDTO> page(PlanPublishDTO dto) {
        return planPublishService.page(PageUtil.buildPage(dto), dto);
    }

    /**
     * 修改套餐列表
     *
     * @param map 请求参数
     */
    @PreAuthorize("@ps.hasPermission('system:planPublishList:edit')")
    @OperatorInfo(title = "修改", operator = OperatorType.UPDATE)
    @PutMapping(value = "/updatePlanPublishList")
    public ApiResultWrapper<Object> updatePublishList(@Validated @RequestBody Map<String, JsonNode> map) {
        JsonNode planPublishList = map.get("planPublishList");
        if (null == planPublishList) {
            return ApiResult.error("planPublishList不能为空");
        }
        try {
            List<PlanPublishList> planPublishLists = objectMapper.readValue(planPublishList.toString(), new TypeReference<>() {
            });
            planPublishService.updatePlanPublishList(planPublishLists);
            planPublishLists.clear();
        } catch (JsonProcessingException e) {
            return ApiResult.error("json转换异常");
        }
        return ApiResult.success("操作成功");
    }
}